/**
 * 登录注册云函数入口文件（重构版）
 */

const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

// 导入工具类
const Response = require('./utils/response')
const Logger = require('./utils/logger')

// 导入Repository层
const UserRepository = require('./repositories/userRepo')
const TokenRepository = require('./repositories/tokenRepo')
const InviteRepository = require('./repositories/inviteRepo')

// 导入Service层
const UserService = require('./services/userService')
const InviteService = require('./services/inviteService')
const AuthService = require('./services/authService')
const SmsService = require('./services/smsService')

// 初始化Repository
const userRepo = new UserRepository(db)
const tokenRepo = new TokenRepository(db)
const inviteRepo = new InviteRepository(db)

// 初始化Service
const userService = new UserService(userRepo)
const inviteService = new InviteService(inviteRepo, userRepo)
const smsService = new SmsService()
const authService = new AuthService(userRepo, tokenRepo, inviteRepo, userService, inviteService, smsService)

/**
 * 云函数入口
 */
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const { action, data } = event

  Logger.info('Login', '收到请求', { action, openid: wxContext.OPENID })

  try {
    let result

    switch (action) {
      // 密码登录
      case 'passwordLogin':
        result = await handlePasswordLogin(data, wxContext)
        break

      // 快速登录（验证码登录）
      case 'quickLogin':
        result = await handleQuickLogin(data, wxContext)
        break

      // 用户注册
      case 'register':
        result = await handleRegister(data, wxContext)
        break

      // 微信授权登录
      case 'wechatLogin':
        result = await handleWechatLogin(wxContext)
        break

      // 微信授权注册
      case 'wechatRegister':
        result = await handleWechatRegister(data, wxContext)
        break

      // 创建邀请码（管理员功能）
      case 'createInviteCode':
        result = await handleCreateInviteCode(data, wxContext)
        break

      // 禁用邀请码（管理员功能）
      case 'disableInviteCode':
        result = await handleDisableInviteCode(data, wxContext)
        break

      // 验证邀请码
      case 'validateInviteCode':
        result = await handleValidateInviteCode(data, wxContext)
        break

      default:
        return Response.error(400, '未知操作')
    }

    return result

  } catch (error) {
    Logger.error('Login', '请求处理失败', error)
    return Response.error(500, error.message || '操作失败')
  }
}

/**
 * 处理密码登录
 */
async function handlePasswordLogin(data, wxContext) {
  const { account, password } = data

  const result = await authService.passwordLogin(account, password, wxContext.OPENID)

  return Response.success({
    token: result.token,
    userInfo: result.userInfo
  }, '登录成功')
}

/**
 * 处理快速登录
 */
async function handleQuickLogin(data, wxContext) {
  const { phone, verifyCode, inviteCode } = data

  const result = await authService.quickLogin(phone, verifyCode, inviteCode, wxContext.OPENID)

  return Response.success({
    token: result.token,
    userInfo: result.userInfo,
    isNewUser: result.isNewUser,
    rewardPoints: result.rewardPoints
  }, result.message)
}

/**
 * 处理用户注册
 */
async function handleRegister(data, wxContext) {
  const result = await authService.register(data, wxContext.OPENID)

  return Response.success({
    token: result.token,
    userInfo: result.userInfo
  }, '注册成功')
}

/**
 * 处理微信授权登录
 */
async function handleWechatLogin(wxContext) {
  const result = await authService.wechatLogin(wxContext.OPENID)

  if (result.needRegister) {
    return Response.success({
      needRegister: true
    }, result.message)
  }

  return Response.success({
    token: result.token,
    userInfo: result.userInfo,
    needRegister: false
  }, '登录成功')
}

/**
 * 处理微信授权注册
 */
async function handleWechatRegister(data, wxContext) {
  const { wechatInfo, phone, verifyCode, inviteCode } = data

  const result = await authService.wechatRegister(
    wechatInfo,
    phone,
    verifyCode,
    inviteCode,
    wxContext.OPENID
  )

  return Response.success({
    token: result.token,
    userInfo: result.userInfo
  }, '注册成功')
}

/**
 * 创建邀请码（管理员功能）
 */
async function handleCreateInviteCode(data, wxContext) {
  const { rewardPoints, remark } = data

  if (!rewardPoints || rewardPoints < 0) {
    return Response.paramError('请设置有效的奖励积分')
  }

  const result = await inviteService.createInviteCode(
    rewardPoints,
    wxContext.OPENID, // 创建者ID（实际应该验证管理员权限）
    remark || ''
  )

  return Response.success({
    code: result.code,
    inviteCodeId: result.inviteCodeId
  }, '邀请码创建成功')
}

/**
 * 禁用邀请码（管理员功能）
 */
async function handleDisableInviteCode(data, wxContext) {
  const { code } = data

  if (!code) {
    return Response.paramError('邀请码不能为空')
  }

  await inviteService.disableInviteCode(code)

  return Response.success(null, '邀请码已禁用')
}

/**
 * 验证邀请码
 */
async function handleValidateInviteCode(data, wxContext) {
  const { code } = data

  const inviteCode = await inviteService.validateInviteCode(code)

  return Response.success({
    code: inviteCode.code,
    rewardPoints: inviteCode.rewardPoints,
    status: inviteCode.status
  }, '邀请码有效')
}

